#include <atomic>

class spinlock {
 private:
  std::atomic_flag flag = ATOMIC_FLAG_INIT;

 public:
  void lock() {
    while (flag.test_and_set(std::memory_order_acquire))
      ;
  }

  void unlock() { flag.clear(std::memory_order_release); }
};

#include <condition_variable>
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

class thread_pool {
 private:
  bool stop;
  std::vector<std::thread> workers;
  std::mutex mtx;
  std::condition_variable cv;
  std::queue<std::function<void()>> tasks;

 public:
  thread_pool(size_t n) : stop(false) {
    for (size_t i = 0; i < n; i++) {
      workers.emplace_back([this] {
        while (true) {
          std::function<void()> task;
          {
            std::unique_lock<std::mutex> lock(mtx);
            cv.wait(lock, [this] { return stop || !tasks.empty(); });
            if (stop & tasks.empty()) {
              break;
            }
            task = std::move(tasks.front());
            tasks.pop();
          }
          task();
        }
      });
    }
  }
  ~thread_pool() {
    {
      std::unique_lock<std::mutex> lock(mtx);
      stop = true;
    }
    cv.notify_all();
    for (auto& t : workers) {
      t.join();
    }
  }

  template <class F, class... Args>
  auto enqueue(F&& f, Args&&... args)
      -> std::future<typename std::result_of<F(Args...)>::type> {
    using retype = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<retype()>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...));

    std::future<retype> res = task->get_future();
    {
      std::unique_lock<std::mutex> lock(mtx);
      if (stop) {
        throw std::runtime_error("enqueue on stopped thread pool");
      }
      tasks.emplace([task]() { (*task)(); });
    }
    cv.notify_one();
    return res;
  }
};

template <class T>
class shared_ptr {
  T* ptr;
  int* count;

 public:
  shared_ptr(T* p = nullptr) : ptr(p), count(new int(1)) {}
  shared_ptr(const shared_ptr& other) : ptr(other), count(other.count) {
    ++(*count);
  }

  shared_ptr& operator=(const shared_ptr& other) {
    if (this != &other) {
      release();
      ptr = other.ptr;
      count = other.count;
      ++(*count);
    }
    return *this;
  }

  ~shared_ptr() { release(); }

  void release() {
    --(*count);
    if (*count == 0) {
      delete ptr;
      delete count;
    }
  }

  T* get() const { return ptr; }
  T& operator*() const { return *ptr; }
  T* operator->() const { return ptr; }
  int use_count() const { return *count; }
  bool unique() const { return *count == 1; }
  explicit operator bool() const { return ptr != nullptr; }
};

#include <iostream>

int main(int argc, char const* argv[]) {
  thread_pool pool(4);
  auto res = pool.enqueue([](int answer) { return answer; }, 42);
  std::cout << res.get() << std::endl;
  return 0;
}